package com.greenold.check.controller;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.greenold.common.core.domain.entity.SysUser;
import com.greenold.common.core.domain.model.LoginUser;
import com.greenold.common.utils.SecurityUtils;
import com.greenold.framework.web.service.SysLoginService;
import com.greenold.residing.service.IContractService;
import com.greenold.system.mapper.SysUserMapper;
import com.greenold.utils.OSSUtils;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.greenold.common.annotation.Log;
import com.greenold.common.core.controller.BaseController;
import com.greenold.common.core.domain.AjaxResult;
import com.greenold.common.enums.BusinessType;
import com.greenold.check.domain.Checkout;
import com.greenold.check.service.ICheckoutService;
import com.greenold.common.utils.poi.ExcelUtil;
import com.greenold.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 退住Controller
 * 
 * @author ruoyi
 * @date 2025-10-13
 */
@RestController
@RequestMapping("/check/checkout")
public class CheckoutController extends BaseController
{
    @Autowired
    private ICheckoutService checkoutService;
    @Autowired
    private RepositoryService repositoryService;


    /**
     * 查询退住列表
     */
    @PreAuthorize("@ss.hasPermi('system:checkout:list')")
    @GetMapping("/list")
    public TableDataInfo list(Checkout checkout)
    {

        // 查询是否已有部署
//        long count = repositoryService.createProcessDefinitionQuery()
//                .processDefinitionKey(processKey)
//                .count();
//
//        if (count == 0) {
//            repositoryService.createDeployment()
//                    .name("退住流程")
//                    .key(processKey)
//                    .addClasspathResource("processes/checkout.bpmn20.xml")
//                    .deploy();
//            System.out.println("✅ 已部署 checkout 流程。");
//        } else {
//            System.out.println("ℹ️ checkout 流程已存在，无需重复部署。");
//        }
        startPage();
        List<Checkout> list = checkoutService.selectCheckoutList(checkout);
        return getDataTable(list);
    }

    /**
     * 导出退住列表
     */
    @PreAuthorize("@ss.hasPermi('system:checkout:export')")
    @Log(title = "退住", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Checkout checkout)
    {

        List<Checkout> list = checkoutService.selectCheckoutList(checkout);
        ExcelUtil<Checkout> util = new ExcelUtil<Checkout>(Checkout.class);
        util.exportExcel(response, list, "退住数据");
    }

    /**
     * 获取退住详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:checkout:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {

        return success(checkoutService.selectCheckoutById(id));
    }

    /**
     * 新增退住
     */
    @PreAuthorize("@ss.hasPermi('system:checkout:add')")
    @Log(title = "退住", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Checkout checkout)
    {
        String s = checkoutService.insertCheckout(checkout);
        if(s.equals("500")){
            return AjaxResult.error("此老人已在办理退住");
        }
        Map<String,String> map =  new HashMap<>();
        map.put("id",s);
        return AjaxResult.success(map);
    }

    /**
     * 修改退住
     */
    @PreAuthorize("@ss.hasPermi('system:checkout:edit')")
    @Log(title = "退住", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Checkout checkout)
    {
        return toAjax(checkoutService.updateCheckout(checkout));
    }

    /**
     * 删除退住
     */
    @PreAuthorize("@ss.hasPermi('system:checkout:remove')")
    @Log(title = "退住", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(checkoutService.deleteCheckoutByIds(ids));
    }


    @PostMapping("/uploadContract")
    public AjaxResult uploadContract(@RequestParam("file") MultipartFile file,@RequestParam("contractNo") String contractNo)
    {
        return AjaxResult.success(checkoutService.uploadFile(file, contractNo));
    }
    @PostMapping("/updateContract")
    public AjaxResult updateContract(@RequestParam("file") MultipartFile file,@RequestParam("contractNo") String contractNo)
    {
        return AjaxResult.success(checkoutService.uploadFile(file, contractNo));
    }

    /*
    * @ param id
    * @ return
    * */
    @GetMapping("/getCheckOutDto/{id}")
    public AjaxResult getCheckOutDto(@PathVariable String id)
    {
        // 删除指定部署ID，true表示级联删除（会删除运行中的流程和历史数据）

        return AjaxResult.success(checkoutService.selectCheckoutDtoById(id));
    }

    @PostMapping("/addBill")
    public AjaxResult addCheckOutBill(@RequestBody Map<String, Object> params) {
        String jsonBill = (String) params.get("jsonBill");
        String id = (String) params.get("id");
        String elderId = (String) params.get("elderId");

        System.out.println("jsonBill = " + jsonBill);
        System.out.println("id = " + id);
        System.out.println("elderId = " + elderId);
        checkoutService.addCheckOutBill(jsonBill, id, elderId);

        return AjaxResult.success();
    }

    @GetMapping("/getActivityUser/{id}")
    public AjaxResult getActivityUser(@PathVariable String id){
        return AjaxResult.success(checkoutService.getActivityUser(id));
    }

    @PostMapping("/approval")
    public AjaxResult approval(@RequestParam String checkoutId,
                               @RequestParam Integer num,
                               @RequestParam String comment) {
        System.out.println("✅ checkoutId = " + checkoutId);
        // 处理逻辑
        return AjaxResult.success( checkoutService.approval(String.valueOf(num), checkoutId, comment));
    }

    //解除协议
    @PostMapping("/removeContract")
    public AjaxResult removeContract(
            @RequestParam("id") String id,
            @RequestParam("fileUrl") String fileUrl,
            @RequestParam("removeData") @DateTimeFormat(pattern = "yyyy-MM-dd") Date removeData) {

        System.out.println("✅ id = " + id);
        System.out.println("✅ fileUrl = " + fileUrl);
        System.out.println("✅ removeData = " + removeData);


        return AjaxResult.success(checkoutService.removeContract(id, fileUrl, removeData));
    }

    /**
     * 上传退租凭证
     * 账单清算
     */
    @PostMapping("/uploadRefundVoucher")
    public AjaxResult uploadRefundVoucher(
            @RequestParam("id") Long id,
            @RequestParam("refundWay") String refundWay,
            @RequestParam(value = "refundAmount", required = false) BigDecimal refundAmount,
            @RequestParam(value = "refundRemark", required = false) String refundRemark,
            @RequestPart("refundVoucher") MultipartFile refundVoucher) {
        System.out.println("✅ id = " + id);
        System.out.println("✅ refundWay = " + refundWay);
        System.out.println("✅ refundAmount = " + refundAmount);
        System.out.println("✅ refundRemark = " + refundRemark);
        System.out.println("✅ refundVoucher = " + refundVoucher);
        checkoutService.uploadRefundVoucher(String.valueOf(id),refundWay,refundAmount,refundRemark,refundVoucher);
        return AjaxResult.success();
    }

    @GetMapping("/getActivityLog/{id}")
    public AjaxResult getActivityLog(@PathVariable String id){
        return AjaxResult.success(checkoutService.getActivityLog(id));
    }
    @GetMapping("/getCheckoutId")
    public AjaxResult getCheckoutId(@RequestParam  String processInstanceId){
        return AjaxResult.success(checkoutService.getCheckoutId(processInstanceId));
    }

    //实验获取用户数据
    @Autowired
    private SysUserMapper sysUserMapper;
    @GetMapping("/getUserData")
    public AjaxResult getUserData(){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = sysUserMapper.selectUserById(loginUser.getUserId());
        return AjaxResult.success(sysUser);
    }

    @PostMapping("/changeAvatar")
    public AjaxResult uploadAvatar(@RequestParam("file") MultipartFile file) throws IOException {
        // 保存文件逻辑
        LoginUser loginUser = SecurityUtils.getLoginUser();
        InputStream inputStream = file.getInputStream();
        String upload = OSSUtils.upload(inputStream, file.getOriginalFilename(), "uploads/img/");
        SysUser user = loginUser.getUser();
        user.setAvatar(upload);
        sysUserMapper.updateUser(user);
        return AjaxResult.success(upload);
    }


}
